import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import { Schema } from 'mongoose';

import { ContactModel, DictionaryModel } from '@server/models';
import { AuthService } from '@server/auth';
import { BaseResponse } from '@server/basic-dto';
import { DIC_TYPE_CODE_NOT_EXIST } from '@server/modules/dictionary/error';

import { CreateContactDto, ContactListResponse } from './dto';

@Injectable()
export default class ContactService {
  constructor(
    private readonly authService: AuthService,
    @Inject('DICTIONARY_MODEL')
    private readonly dictionaryModel: typeof DictionaryModel,
    @Inject('CONTACT_MODEL') private readonly contactModel: typeof ContactModel,
  ) {}

  async addContact(createContact: CreateContactDto): Promise<BaseResponse> {
    const count: number = await this.dictionaryModel.countDocuments({
      _id: {
        $in: [
          createContact.companyType,
          createContact.country,
          createContact.locale,
        ],
      },
    });

    if (count < 3) {
      throw new BadRequestException(DIC_TYPE_CODE_NOT_EXIST);
    }

    await this.contactModel.create(createContact);

    return {
      code: 0,
      message: '',
    };
  }

  async list(
    page: number = 1,
    pageSize: number = 10,
    keyword: string = ''
  ): Promise<ContactListResponse> {
    const query: {
      message?: {
        $regex: string;
        $options: string;
      }
    } = {}

    if (keyword) {
      query.message = {
        $regex: keyword,
        $options: '$i'
      }
    }

    const data: any = await this.contactModel.paginate({
      query,
      page: parseInt(`${page}`),
      limit: parseInt(`${pageSize}`),
    });

    return {
      code: 0,
      message: '',
      data,
    };
  }
}
